package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<Address> findList() {
        //查询当前用户的地址列表
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        List<Address> addressList = addressMapper.selectList(wrapper);
        return addressList;
    }

    //新增用户地址
    @Override
    public void save(Address address) {
        //1.补齐参数
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);//设置为非默认地址
        addressMapper.insert(address);

    }

    //设置默认地址
    @Override
    public void setDefault(Long id) {
        //1.将当前用户的所有地址设置为非默认0
        //update address_book set is_default = 0 where user_id = #{登录用户id}
        //1-1 设置跟新字段
        Address address = new Address();
        address.setIsDefault(0);//非默认地址

        //1-2 设置更新条件
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());

        //1-3 执行更新
        addressMapper.update(address, wrapper);

        //2.将当前id设置为默认地址
        //update address_book set is_default = 0 where id = #{前端传入id}
        address.setIsDefault(1);
        address.setId(id);
        addressMapper.updateById(address);

    }

    //查询默认地址
    @Override
    public Address finDefault() {
        //查询当前用户is_default=1的记录
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId())
                .eq(Address::getIsDefault, 1);//默认地址

        return addressMapper.selectOne(wrapper);
    }

    /**
     * 根据主键返回
     */
    @Override
    public Address findById(Long id) {
        Address address = addressMapper.selectById(id);
        return address;
    }

    /*
     * 修改地址
     * */
    @Override
    public void update(Address address) {
        addressMapper.updateById(address);
    }

    /*
     * 删除地址
     * */
    @Override
    public void deleteById(Long ids) {
        addressMapper.deleteById(ids);
    }
}
